package sanshui.system.trade.factory.report;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import sanshui.system.trade.db.entity.TradeReport;
import sanshui.system.trade.factory.trade.TradeSystemContext;
import sanshui.system.trade.model.*;
import sanshui.system.trade.util.CommonHttpUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 回测报告任务
 * */
@Component
@Slf4j
public class ReportTask {

    @Resource
    RestTemplate restTemplate;

    @Value("${bk.report.url}")
    private String bkUrl;
    @Value("${bk.wencai.url}")
    private String wencaiUrl;

    /**
     * 通过Python获得问财结果
     * */
    public WenCaiModel wencaiByPython(String question){
        log.info("开始-问财-python， question:{}", question);
        WenCaiModel wenCaiModel = new WenCaiModel();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("qs", question);
        String response = CommonHttpUtil.post(restTemplate, wencaiUrl, JSONObject.toJSONString(jsonObject));
        if (Strings.isNotEmpty(response)){
            List<StockInfoModel> models = JSONObject.parseArray(response, StockInfoModel.class);
            wenCaiModel.setCodeInfoList(models);
            return wenCaiModel;
        }
        log.error("无法获取问财报告");
        return null;
    }
    /**
     * 通过Python生成交易报告
     * */
    public TradeReport generateBackTradeReportByPython(TradeReportRequestModel requestModel){
        log.info("开始-生成回测交易报告-python， userId:{}, accId:{}, start:{}, end:{}", requestModel.getUserId(), requestModel.getAccId(), requestModel.getStartDate(), requestModel.getEndDate());
        String response = CommonHttpUtil.post(restTemplate, bkUrl, JSONObject.toJSONString(requestModel));
        if (Strings.isNotEmpty(response)){
            ReportResponseModel responseModel = JSONObject.parseObject(response, ReportResponseModel.class);
            TradeReport tradeReport = new TradeReport();
            BeanUtils.copyProperties(responseModel, tradeReport);
            tradeReport.setTotalValue(new BigDecimal(tradeReport.getTotalValue())
                    .setScale(2, RoundingMode.HALF_UP).toPlainString());
            tradeReport.setPicUrl(requestModel.getPicPath());
            return tradeReport;
        }
        log.error("无法获取回测报告， userId:{}, accId:{}, start:{}, end:{}", requestModel.getUserId(), requestModel.getAccId(), requestModel.getStartDate(), requestModel.getEndDate());
        return null;
    }
}
